#include "packet_controller.h"

namespace Controller
{
    PacketController::PacketController(std::shared_ptr<httplib::Server> server, std::shared_ptr<Tshark::TsharkManager> manager)
        : BaseController(server, manager)
    {
    }

    void PacketController::registerRoute()
    {
        m_server->Post("/api/getPacketList",
                       [&](const httplib::Request &req, httplib::Response &resp)
                       { this->getPacketList(req, resp); });

        m_server->Post("/api/analysisFile",
                       [&](const httplib::Request &req, httplib::Response &resp)
                       { this->analysisFile(req, resp); });
    }

    void PacketController::getPacketList(const httplib::Request &req, httplib::Response &resp)
    {
        try
        {
            if (m_tsharkManager->getWorkStatus() != Tshark::WorkStatus::STATUS_IDLE)
            {
                this->sendErrorResponse(resp, ERROR_STATUS_WRONG);
                return;
            }
            Tshark::QueryConditon condition;
            if (!this->parseQueryCondition(req, condition))
            {
                this->sendErrorResponse(resp, ERROR_PARAMETER_WRONG);
                return;
            }
            std::vector<std::shared_ptr<Tshark::DataType::Packet>> packets;
            if (!this->m_tsharkManager->queryPackets(condition, packets))
            {
                this->sendErrorResponse(resp, ERROR_DATABASE_WRONG);
                return;
            }
            this->sendDataList(resp, packets);
        }
        catch (const std::exception &e)
        {
            this->sendErrorResponse(resp, ERROR_INTERNAL_WRONG);
        }

        // 以下部分重新实现，由子类负责实现request的body解析
        /*
        std::string reqBodyStr = req.body.c_str();
        std::string errMsg;
        Json::Value reqBodyJson;
        Json::CharReaderBuilder builder;
        const std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
        if (!reader->parse(reqBodyStr.c_str(), reqBodyStr.c_str() + reqBodyStr.size(), &reqBodyJson, &errMsg))
        {
            LOG_F(ERROR, "request parse %s error: %s", reqBodyStr.c_str(), errMsg.c_str());
            resp.status = 400;
            resp.set_content("error", "text/plain");
            return;
        }
        Tshark::QueryConditon condition;
        if (reqBodyJson.isMember("ip") && reqBodyJson["ip"].isString())
        {
            condition.ip = reqBodyJson["ip"].asString();
        }

        if (reqBodyJson.isMember("port") && reqBodyJson["port"].isInt())
        {
            condition.port = reqBodyJson["port"].asInt();
        }

        if (reqBodyJson.isMember("mac") && reqBodyJson["mac"].isString())
        {
            condition.mac = reqBodyJson["mac"].asString();
        }

        if (reqBodyJson.isMember("location") && reqBodyJson["location"].isString())
        {
            condition.location = reqBodyJson["location"].asString();
        }

        if (reqBodyJson.isMember("proto") && reqBodyJson["proto"].isString())
        {
            condition.proto = reqBodyJson["proto"].asString();
        }
        std::vector<std::shared_ptr<Tshark::DataType::Packet>> packets;
        // 将packets序列化为response的json字符串
        Json::Value respJson, respData;
        Json::StreamWriterBuilder writerBuilder;
        if (!m_tsharkManager->queryPackets(condition, packets)) // 查找失败
        {
            resp.status = 400;
            resp.set_content("error", "text/plain");
            return;
        }
        for (auto &packet : packets)
        {
            respData.append(packet->to_json());
        }
        respJson["data"] = respData;
        respJson["status"] = 200;
        respJson["code"] = 0;
        respJson["msg"] = "success";
        std::string respStr = Json::writeString(writerBuilder, respJson);
        resp.set_content(respStr, "application/json");*/
    }

    void PacketController::analysisFile(const httplib::Request &req, httplib::Response &resp)
    {
        try
        {
            if (req.body.empty())
            {
                sendErrorResponse(resp, ERROR_PARAMETER_WRONG);
                return;
            }
            // 判断状态是否空闲
            if (m_tsharkManager->getWorkStatus() != Tshark::WorkStatus::STATUS_IDLE)
            {
                sendErrorResponse(resp, ERROR_STATUS_WRONG);
                return;
            }
            Json::CharReaderBuilder builder;
            std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
            Json::Value reqBodyJson;
            std::string errMsg;
            if (!reader->parse(req.body.c_str(), req.body.c_str() + req.body.size(), &reqBodyJson, &errMsg))
            {
                sendErrorResponse(resp, ERROR_PARAMETER_WRONG);
                return;
            }
            if (!reqBodyJson.isMember("filePath") || !reqBodyJson["filePath"].isString())
            {
                sendErrorResponse(resp, ERROR_PARAMETER_WRONG);
                return;
            }
            std::string filePath = reqBodyJson["filePath"].asString();
            if (m_tsharkManager->analysisFile(filePath) == Tshark::error_code::success)
            {
                sendSuccessResponse(resp);
            }
            else
            {
                sendErrorResponse(resp, ERROR_TSHARK_WRONG);
            }
        }
        catch (const std::exception &e)
        {
            sendErrorResponse(resp, ERROR_INTERNAL_WRONG);
        }
    }
}